package com.yc.snack.filter;

import com.yc.snack.util.StringUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**字符编码集过滤器
 * @Auther: HuYang
 * @Date: 2022/11/6 - 11 - 06 - 21:55
 * @Description: com.yc.snack.filter
 * @version: 1.0
 */

@WebFilter(value = "/*", filterName ="CharacterEncodingFilter",
        initParams = {@WebInitParam(name="encoding",value = "utf-8")})
public class CharacterEncodingFilter implements Filter {
    private String encoding = "utf-8";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String temp = filterConfig.getInitParameter("encoding");
        if(!StringUtil.checkNull(temp)){
            encoding = temp;
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        req.setCharacterEncoding(encoding);
        resp.setCharacterEncoding(encoding);

        chain.doFilter(req,resp);//将转码之后的请求和响应对象传给下一个过滤器
    }
}
